package com.download.web.pay;

import com.blade.exception.ValidatorException;
import com.blade.ioc.annotation.Inject;
import com.blade.kit.JsonKit;
import com.download.web.entity.BusOrder;
import com.download.web.pay.entity.*;
import com.download.web.pay.enums.OrderStatus;
import com.download.web.pay.enums.PlatFormEnum;
import com.download.web.service.IBusOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * Make Money Service
 *
 * @author biezhi
 * @date 2018/9/28
 */
@Slf4j
@Service
public class MakeMoneyService {

    @Autowired
    private IBusOrderService orderService;

    @Autowired
    private PayApi payApi;



    public PayOrderResponse createOrder(BusOrder order) throws UnsupportedEncodingException {
//        order.setMoney(order.getMoney().multiply(order.getMoney()));
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
        String orderNo = dateFormat.format(new Date())+ Math.random()*10000;
        order.setOrderStatus(0);
//        order.setPlatform(Platform.YOUZAN.toString().toLowerCase());
        order.setOrderNum(orderNo);
        order.setCreateTime(new Date());
        PayOrderResponse payOrderResponse = null;
//        try {
            // 调用支付接口
            Response<QRCodeResponse> resultResponse = getPayOrderResponse(order);

            if (resultResponse.getErrorResponse()!=null&&resultResponse.getErrorResponse().getMsg()!=null){
                throw new ValidatorException(new String(resultResponse.getErrorResponse().getMsg().getBytes(),"utf-8"));
            }else {
                QRCodeResponse response = resultResponse.getResponse();
                payOrderResponse = new PayOrderResponse();
                payOrderResponse.setTradeNo(response.getQrId().toString());
                payOrderResponse.setQrImg(response.getQrCode());
                payOrderResponse.setQrUrl(response.getQrUrl());
            }
            order.setTradeNo(payOrderResponse.getTradeNo());
            orderService.save(order);
//            this.addCount();
//            Constant.TRADE_NOS.add(payOrderResponse.getTradeNo());
            return payOrderResponse;
       /* } catch (Exception e) {
            log.error("保存订单异常", e);
            throw new ValidatorException("创建订单失败");
        }*/
//        return payOrderResponse;
    }

    private Response<QRCodeResponse> getPayOrderResponse(BusOrder order) {
//        if (PlatFormEnum.YOUZAN.toString().equalsIgnoreCase(order.getPlatform())) {
            CreateOrderRequest createOrderRequest = new CreateOrderRequest();
            createOrderRequest.setPrice(order.getMoney());
            createOrderRequest.setQrName(order.getPayComment());

            return payApi.createQrCode(createOrderRequest);
//        }

//        throw new ValidatorException("暂不支持交易");
    }

    /**
     * 支付渠道支付回调
     *
     * @param platform 支付渠道
     * @param body     返回消息体
     */
    public void execCallback(PlatFormEnum platform, String body) {
        if (PlatFormEnum.YOUZAN.equals(platform)) {
            CallbackTrade callbackTrade = JsonKit.formJson(body, CallbackTrade.class);
            if (!callbackTrade.getTest() && "trade_TradePaid".equals(callbackTrade.getType())) {
                // 支付成功
                if ("PAID".equals(callbackTrade.getStatus())) {
                    String msg = Utils.decode(callbackTrade.getMsg());
                    log.info("有赞支付回调msg: {}", msg);

                    int start = msg.indexOf("qr_id\"");
                    int end   = msg.indexOf(",", start);

                    String qrId = msg.substring((start + 7), end);
                    updatePaySuccess(qrId, OrderStatus.PAY_SUCCESS.getStatus());
                }
            }
        }
    }

    public void updatePaySuccess(String tradeNo, Integer orderStatus) {
        /*BusOrder order = select().from(Order.class).where(Order::getTradeNo, tradeNo).one();
        if (null == order || OrderStatus.PAY_SUCCESS.getStatus() == order.getOrderStatus()) {
            return;
        }*/

//        update().from(Order.class).set(Order::getOrderStatus, orderStatus).where(Order::getTradeNo, tradeNo).execute();

        /*// 总金额+money
        String totalAmount = findOption(Constant.TOTAL_AMOUNT);
        optionService.update(Constant.TOTAL_AMOUNT, new BigDecimal(totalAmount).add(order.getMoney()).toString());

        // 今天金额+money
        String todayAmount = findOption(Constant.TODAY_AMOUNT);
        optionService.update(Constant.TODAY_AMOUNT, new BigDecimal(todayAmount).add(order.getMoney()).toString());
*/
    }

   /* private void addCount() {
        // 总笔数+1
        String totalCount = findOption(Constant.TOTAL_COUNT);
        optionService.update(Constant.TOTAL_COUNT, String.valueOf(new BigDecimal(totalCount).intValue() + 1));

        // 今天笔数+1
        String todayCount = findOption(Constant.TODAY_COUNT);
        optionService.update(Constant.TODAY_COUNT, String.valueOf(Integer.valueOf(todayCount) + 1));
    }*/

    /*public boolean checkOrderPaySuccess(String tradeNo) {
        if (Platform.YOUZAN.toString().equalsIgnoreCase(Bootstrap.getGlobalConfig().get(Constant.SAFE_PLATFORM))) {
            return Bootstrap.payApi.orderPaySuccess(tradeNo);
        }
        return false;
    }*/



}
